package com.initialize.core.security.service;

import com.initialize.common.mybatis.plus.entity.Role;
import com.initialize.core.security.entity.RoleI;
import com.initialize.core.security.entity.UserI;
import com.initialize.service.api.system.entity.UserInfo;
import com.initialize.service.api.system.resttemplate.impl.UserRestTemplateImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: jane
 * Date: 2020/1/2
 * Time: 7:43 下午
 * Description:
 * import com.initialize.service.api.system.feign.IUserClient;
 */
@Slf4j
@Service("securityUserService")
public class UserService implements UserDetailsService {

    final
    UserRestTemplateImpl userRestTemplate;

    public UserService(UserRestTemplateImpl userRestTemplate) {
        this.userRestTemplate = userRestTemplate;
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserInfo user = userRestTemplate.findByUsername(s);

        log.info("user->>   {}", user.toString());
        List<RoleI> roleIList = new ArrayList<>();


        List<Role> roles = user.getRoles();
        roles.forEach(o -> {
            RoleI roleI = new RoleI();
            roleI.setId(o.getId());
            roleI.setRole(o.getRole());
            roleIList.add(roleI);
        });

        return UserI.builder()
                .roles(roleIList)
                .password(user.getPassword())
                .userName(user.getUserName())
                .build();
    }
}